import javax.microedition.lcdui.Image;

public class FontImage {
	
	private Image bigImg;
	private Image[] imgs;
	
	public int pieceHeight;
	private int number;
	public int sourceWidth;
	
	public int maxWidth;
	
	private char[] chars;
	
	public FontImage(String file, char[] chars, int pieceHeight) {
		this.chars = chars;
		this.pieceHeight = pieceHeight;
		try {
			bigImg = Image.createImage(file);
			sourceWidth = bigImg.getWidth();
			
			number = chars.length;
			imgs = new Image[number];
			
			setupImgs();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	private void setupImgs() {
		int y = 0;
		maxWidth = 0;
		for (int i = 0; i < number; i++) {
			imgs[i] = Image.createImage(bigImg, 0, y, sourceWidth, pieceHeight, 0);
			imgs[i] = trim(imgs[i]);
			y += pieceHeight;
		}
	}
	
	private Image trim(Image img) {
		int width = img.getWidth();
		int height = img.getHeight();
		int[] rgbData = new int[width * height];
		img.getRGB(rgbData, 0, width, 0, 0, width, height);
		
		int i = rgbData.length - 1;
		boolean found = false;
		while (true) {
			if (!isFullTrans(rgbData[i])) {
				found = true;
				break;
			}
			if (i == 0) break;
			if (i < width) {
				i += width * (height - 1) - 1;
			} else {
				i -= width;
			}
		}
		
		if (!found) return img;
		width = i % width + 1;
		if (width > maxWidth) maxWidth = width;
		return Image.createImage(img, 0, 0, width, height, 0);
	}
	
	private boolean isFullTrans(int pixel) {
		return (pixel & 0xFF000000) == 0;
	}
	
	public Image cropImage(char c) {
		for (int i = 0; i < number; i++) {
			if (chars[i] == c) {
				return imgs[i];
			}
		}
		return null;
	}

}
